package org.idea.spring.bean.beandestory;

import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent;

/**
 * @Author idea
 * @Date created in 5:19 下午 2020/7/18
 */
public class BeanDestoryDemo implements ApplicationListener<ContextClosedEvent> {

    private static AnnotationConfigApplicationContext applicationContext;

    public static void main(String[] args) {
        applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(BeanDestoryDemo.class);
        applicationContext.register(User.class);
        applicationContext.refresh();
        DestoryUserBeanFactory destoryUserBeanFactory = applicationContext.getBean(DestoryUserBeanFactory.class);
        System.out.println("spring上下文准备关闭");
        applicationContext.close();
        System.out.println("spring上下文已经关闭");
    }

    @Bean(destroyMethod = "destory2",initMethod = "init2")
    public DestoryUserBeanFactory createDestoryUserBeanFactory() {
        return new DestoryUserBean();
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        System.out.println("获取到关闭事件");
        User user = applicationContext.getBean(User.class);
        System.out.println(user);
    }
}
